<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色表格 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 权限 tree 树 -->
            <el-row
              :gutter="20"
              :class="['dbbottom', i1 === 0 ? 'dbtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  type="primay"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 二、三级权限渲染 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'dbtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级渲染 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级渲染 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialog"
      width="50%"
      @close="rolesDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="rolesForm"
        ref="rolesFormRef"
        :rules="rolesFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="rolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="editRolesDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editRolesForm"
        ref="editRolesFormRef"
        :rules="rolesFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="closeRightDialog"
    >
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        show-checkbox
        :highlight-current="true"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 添加角色对话框
      addRolesDialog: false,
      rolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色的验证规则
      rolesFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 3~10 个字符之间",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 3~10 个字符之间",
            trigger: "blur",
          },
        ],
      },
      // 编辑角色对话框的显示与隐藏
      editRolesDialogVisible: false,
      // 编辑角色的数据
      editRolesForm: {},

      // 分配权限的对话框
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点ID值数组
      defKeys: [],
      // 角色id
      roleId: ''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      let { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
    },

    // 添加角色对话框的显示与隐藏
    addRoles() {
      this.addRolesDialog = true;
    },

    // 关闭添加角色对话框后重置表单
    rolesDialogClose() {
      // 重置表单
      this.$refs.rolesFormRef.resetFields();
    },

    // 发请求添加角色
    rolesInfo() {
      // 先进行表单的预验证
      this.$refs.rolesFormRef.validate(async (vali) => {
        if (!vali) return;
        let { data: res } = await this.$http.post("roles", this.rolesForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        // 提示用户添加成功
        this.$message.success("添加角色成功！");
        // 重新加载数据
        this.getRolesList();
        // 关闭对话框
        this.addRolesDialog = false;
      });
    },

    // 点击编辑按钮显示对话框
    editRolesDialog(roles) {
      this.editRolesDialogVisible = true;
      let newRoles = {};
      newRoles.roleName = roles.roleName;
      newRoles.roleDesc = roles.roleDesc;
      newRoles.id = roles.id;
      this.editRolesForm = newRoles;
    },

    // 关闭编辑角色对话框重置表单
    editRolesDialogClose() {
      this.$refs.editRolesFormRef.resetFields();
    },

    // 发送请求修改角色数据
    editRoles() {
      this.$refs.editRolesFormRef.validate(async (vali) => {
        if (!vali) return;
        let { data: res } = await this.$http.put(
          "roles/" + this.editRolesForm.id,
          this.editRolesForm
        );
        if (res.meta.status !== 200)
          return this.$message.error("更新信息失败！");
        this.$message.success("更新信息成功！");
        this.getRolesList();
        this.editRolesDialogVisible = false;
      });
    },

    // 删除角色
    async removeRole(id) {
      let remove = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 判断返回值 是否 删除
      if (remove !== "confirm") return this.$message.info("已取消删除！");
      let { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getRolesList();
    },

    // 根据 id 删除对应的权限
    async removeRightById(role, rightId) {
      // 提示用户是否确定要删除
      const confirmResutle = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 判断 用户的选择
      if (confirmResutle !== "confirm") {
        return this.$message.info("已取消了删除！");
      }

      // 发送请求删除对应的 权限
      let { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      role.children = res.data;
    },

    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 在对话框展示出来之前发送请求获取权限数据
      let { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.rightsList = res.data;

      this.setRightDialogVisible = true;

      // 使用递归获取三级权限id
      this.getLeafKeys(role,this.defKeys)
    },

    // 通过递归的方式获取 角色下的三级权限id 并包存到 defKeys 的数组中
    getLeafKeys(node,arr) {
      // 递归出口
      if(!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeafKeys(item,arr))
    },

    // 关闭对话框清空 defKeys 数组
    closeRightDialog() {
      this.defKeys = []
    },

    // 点击对话框 确定 按钮分配角色权限
   async allotRights() {
     // 定义一个数据收集 tree 中的id用来发送请求的请求体参数
     const keys = [
       ...this.$refs.treeRef.getCheckedKeys(),
       ...this.$refs.treeRef.getHalfCheckedKeys()
     ]
     const idStr = keys.join(',')
     // 发请求
     let {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
     if(res.meta.status !== 200) return this.$message.error('分配权限失败！')
     this.$message.success('分配权限成功！')
    this.getRolesList()
    this.setRightDialogVisible = false

    }


  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.dbtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>